package com.mrjoew.weekend.web.shopapi;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.mrjoew.weekend.configurations.ScaffoldProperties;
import com.mrjoew.weekend.entities.dto.shop.GoodsDTO;
import com.mrjoew.weekend.entities.po.shop.GoodsPO;
import com.mrjoew.weekend.services.shop.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Christopher Jones
 * @explain
 * @date 2020/11/5 0005 19:48
 */
@Slf4j
@Api(tags = "商城商品")
@CrossOrigin
@RequestMapping(value = "/shop-api/goods")
@RestController
public class GoodsApiController {

    @Autowired
    private ScaffoldProperties scaffoldProperties;

    private final GoodsService goodsService;

    public GoodsApiController(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    @ApiOperation("获取所有商品列表")
    @GetMapping(value = {"", "list"})
    public String list(@RequestBody GoodsDTO condition, @PageableDefault(size = 20) Pageable pageable) {
        JSONObject result = new JSONObject();
        result.put("state", 1);
        result.put("data", goodsService.list(condition, pageable));
        return result.toJSONString();
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @ApiOperation("商品详情")
    @GetMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id") Integer id) {
        JSONObject result = new JSONObject();
        result.put("state", 1);
        result.put("data", goodsService.get(id));
        return result.toJSONString();
    }

    /**
     * @param response
     * @throws IOException
     */
    @ApiOperation("下载商品上传模板")
    @GetMapping(value = "/export")
    public void export(HttpServletResponse response) throws IOException {
        String xlsxSavePath = String.format("%s/商品上传模板.xlsx", scaffoldProperties.getBaseFilePath());

        File xlsx = new File(xlsxSavePath);
        if (!xlsx.exists()) {
            List<String> row1 = CollUtil.newArrayList("品牌", "分类", "CPU", "系统", "屏幕", "价格", "是否优惠", "优惠价", "展示图地址");
            List<String> row2 = CollUtil.newArrayList("", "", "", "", "", "", "", "", "");

            List<List<String>> rows = CollUtil.newArrayList(row1, row2);
            for (int i = 0; i < 100; i++) {
                rows.add(row2);
            }

            File file = new File(scaffoldProperties.getBaseFilePath());
            if (!file.exists()) {
                file.mkdir();
            }

            // 通过工具类创建writer
            ExcelWriter writer = ExcelUtil.getWriter(xlsxSavePath);
            // 通过构造方法创建writer
            // ExcelWriter writer = new ExcelWriter("d:/writeTest.xls");

            // 跳过当前行，既第一行，非必须，在此演示用
            writer.passCurrentRow();

            // 合并单元格后的标题行，使用默认标题样式
            writer.merge(row1.size() - 1, "商品上传模板");
            // 一次性写出内容，强制输出标题
            writer.write(rows, true);
            // 关闭writer，释放内存
            writer.close();
        }
        /*else {
            OutputStream os = response.getOutputStream();
            writer.flush(os, true);
            writer.close();
            IoUtil.close(os);
        }*/

        try (InputStream is = new FileInputStream(xlsxSavePath); OutputStream os = response.getOutputStream()) {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode("商品上传模板.xlsx", "UTF-8"));

            int len = 0;
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        }
    }

    /**
     * 上传商品信息
     *
     * @return
     */
    @ApiOperation("上传商品Excel")
    @PostMapping(value = "/upload")
    public JSONObject upload(@RequestParam("file") MultipartFile file) throws IOException {
        JSONObject result = new JSONObject();

        if (file.isEmpty()) {
            result.put("error", "请选择上传文件!");
            return result;
        }

        File tmpPath = new File(scaffoldProperties.getBaseFilePath());
        if (!tmpPath.exists()) {
            tmpPath.mkdirs();
        }

        File tmpXlsxFile = new File(String.format("%s/%d.xlsx", tmpPath, System.currentTimeMillis()));
        file.transferTo(tmpXlsxFile);

        ExcelReader reader = ExcelUtil.getReader(tmpXlsxFile);
        // List<GoodsPO> goodsPOS = reader.readAll(GoodsPO.class);
        List<List<Object>> readAll = reader.read();

        List<GoodsPO> goodsPOS = new ArrayList<>();
        for (int i = 2; i < readAll.size(); i++) {
            List<Object> t = readAll.get(i);
            String isDiscounts = String.valueOf(t.get(6));
            String discountPrice = String.valueOf(t.get(7));
            GoodsPO goodsPO = new GoodsPO(String.valueOf(t.get(0)), String.valueOf(t.get(1)), String.valueOf(t.get(2)),
                    String.valueOf(t.get(3)), String.valueOf(t.get(4)), new BigDecimal(String.valueOf(t.get(5))),
                    isDiscounts != null && isDiscounts.equals("是") ? 1 : 0,
                    (discountPrice != null && !"".equals(discountPrice)) ? new BigDecimal(discountPrice) : new BigDecimal(0),
                    String.valueOf(t.get(8)));
            goodsPO.setTitle(String.valueOf(t.get(0)));
            goodsPOS.add(goodsPO);
        }

        tmpXlsxFile.delete();
        goodsService.saveAll(goodsPOS);

        result.put("state", 1);
        return result;
    }
}
